#include <queue.h>

#include <cstdio>
#include <cstdlib>

Status LinkQueue_Init(LinkQueue &Q) {
    Q.front = (QueuePtr) malloc(sizeof(QNode));
    if (!Q.front)return OVERFLOW;
    Q.front->next = NULL;
    Q.rear = Q.front;
    Q.length = 0;
    return OK;
}

Status LinkQueue_En(LinkQueue &Q,QElemType e) {
    QueuePtr p = (QueuePtr) malloc(sizeof(QNode));
    if (!p)return ERROR;
    p->data = e;
    p->next = Q.rear->next;
    Q.rear->next = p;
    Q.rear = p;
    Q.length += 1;
    return OK;
}

Status LinkQueue_De(LinkQueue &Q,QElemType &e) {
    if (Q.front == Q.rear) {
        return ERROR;
    }

    QueuePtr p = Q.front->next;
    e = p->data;
    Q.front->next = p->next;
    if (p == Q.rear)Q.rear = Q.front;

    free(p);
    Q.length -= 1;
    return OK;
}

int LinkQueue_Length(LinkQueue Q) {
    return Q.length;
}

void LinkQueue_Clear(LinkQueue &Q) {
    while (Q.length) {
        QElemType e;
        LinkQueue_De(Q, e);
    }
    Q.length = 0;
}

void LinkQueue_Destroy(LinkQueue &Q) {
    LinkQueue_Clear(Q);
    free(Q.front);
}

Status LinkQueue_Empty(LinkQueue Q) {
    return !Q.length;
}

Status LinkQueue_Display(LinkQueue Q) {
    QueuePtr p = Q.front->next;
    int first = 1;
    while (p != NULL) {
        if (first) {
            first = 0;
            printf("队首|");
        } else {
            printf("<==");
        }
        printf("%d", p->data);
        p = p->next;
    }
    printf("|队尾");
    return OK;
}
